package com.android.lmy;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.android.lmy.LitePalDemo.Movie;
import com.android.lmy.SqlLiteDemo.DatabaseHelper;
import com.android.lmy.SqlLiteDemo.StudentDao;

import org.litepal.LitePal;

import java.util.List;

import static org.litepal.util.Const.TableSchema.TABLE_NAME;

/**
 * @功能:
 * @Creat 2020/1/8 15:40
 * @User Lmy
 * @Compony JinAnChang
 */
public class DatabaseProvider extends ContentProvider {
    //创建authority
    public static final String AUTHORITY = "com.android.lmy.DatabaseProvider";
    //匹配成功后的匹配码
    private static final int MATCH_CODE = 100;

    private static UriMatcher uriMatcher;


    //数据改变后指定通知的Uri
    private static final Uri NOTIFY_URI = Uri.parse("content://" + AUTHORITY + "/student");

    static {
        //匹配不成功返回NO_MATCH(-1)
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        //添加我们需要匹配的uri
        uriMatcher.addURI(AUTHORITY, "student", MATCH_CODE);
    }

    @Override
    public boolean onCreate() {
        return false;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection,
                        @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        int match = uriMatcher.match(uri);
        if (match == MATCH_CODE) {
            return StudentDao.getInstance(getContext()).getStudentCursor();
        }

        return null;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        if (uriMatcher.match(uri) == MATCH_CODE) {
            StudentDao.getInstance(getContext()).addstudentCursor(values);
            notifyChange();
        }
        return null;
    }


    private void notifyChange() {
        getContext().getContentResolver().notifyChange(NOTIFY_URI, null);
    }


    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        if (uriMatcher.match(uri) == MATCH_CODE) {
            int type = StudentDao.getInstance(getContext()).deletestudent(selection,selectionArgs);
            notifyChange();
            return type;
        }
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        if (uriMatcher.match(uri) == MATCH_CODE) {
            int type = StudentDao.getInstance(getContext()).updatestudent(values, selection);
            notifyChange();
            return type;
        }
        return 0;
    }
}
